package com.mz.ozy.activity.me;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.mz.ozy.R;
import com.mz.ozy.activity.home.HomeActivity1;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.AddressBean;
import com.mz.ozy.bean.AddressListBean;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.AddressPresenter;
import com.mz.ozy.mvp.view.AddressContract;
import com.mz.ozy.utils.AddrDbManager;
import com.mz.ozy.utils.KeyboardUtils;
import com.mz.ozy.utils.LocationHelper;
import com.mz.ozy.utils.ToastUtils;
import com.yanzhenjie.permission.AndPermission;

import androidx.annotation.Nullable;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by administrator on 2018/11/21.
 * 收货地址 添加/编辑
 */
public class AddressEditActivity extends BaseActivity<AddressContract.View, AddressPresenter> implements AddressContract.View {

    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    @BindView(R.id.et_detail)
    EditText mEtDetail;

    //地址相关
    private OptionsPickerView optionView;
    private String provinceStr, cityStr, areaStr = "";
    private String provinceId = "";
    private String cityId = "";
    private String areaId = "";

    private int type;  //0-增加  1-编辑
    private AddressBean bean;

    /**
     * @param context
     * @param type
     * @param bean
     */
    public static void go(Context context, int type, AddressBean bean) {
        Intent intent = new Intent(context, AddressEditActivity.class);
        intent.putExtra("data", bean);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_edit);
        ButterKnife.bind(this);
        initTitle();
        tvCenterTitle.setText("添加收货地址");
        EventBus.getDefault().register(this);
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void init() {
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            bean = (AddressBean) getIntent().getSerializableExtra("data");
            mEtName.setText(bean.getConsignee());
            mEtPhone.setText(bean.getContactnumber());
            mTvAddress.setText(bean.getArea0name() + bean.getArea1name() + bean.getArea2name());
            mEtDetail.setText(bean.getXxaddress());
            provinceId = bean.getArea0id();
            cityId = bean.getArea1id();
            areaId = bean.getArea2id();
        }
    }

    @OnClick({R.id.ll_address, R.id.bt_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_address:
                KeyboardUtils.hideKeyboard(mEtName);
                showAddressDialog();
                break;
            case R.id.bt_confirm:
                onSubmit();
                break;
        }
    }

    private void onSubmit() {
        String name = mEtName.getText().toString().trim();
        String phone = mEtPhone.getText().toString().trim();
        String detail = mEtDetail.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showToast("请输入收货人姓名");
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showToast("请输入联系电话");
            return;
        }
        if (phone.length() != 11) {
            ToastUtils.showToast("请输入正确手机号码");
            return;
        }
        if (TextUtils.isEmpty(provinceId)) {
            ToastUtils.showToast("请选择省市区");
            return;
        }

        if (TextUtils.isEmpty(detail)) {
            ToastUtils.showToast("请填写详细地址");
            return;
        }
        if (detail.length() < 5) {
            ToastUtils.showToast("详细地址不少于5个字");
            return;
        }
        //都设置为默认地址
        if (type == 0) {
            mPresenter.onAdd(this, name, phone, detail, provinceId, cityId, areaId, "0");
        } else {
            mPresenter.onUpdate(this, bean.getId() + "", name, phone, detail, provinceId, cityId, areaId);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        //刷新购物车
        if (event.getCode() == Constants.EventCode.ADDERESS_DB_READ_SUCCESS) {
            ToastUtils.showToast("地址数据加载成功");
        }
    }

    /**
     * 显示地址弹窗
     */
    private void showAddressDialog() {
        if (AddrDbManager.isLoadAddress && AddrDbManager.options3Items.size() > 0) {
            if (optionView == null) {
                optionView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        provinceStr = AddrDbManager.options1Items.get(options1).getAreaName();
                        provinceId = AddrDbManager.options1Items.get(options1).getId();
                        cityStr = AddrDbManager.options2Items.get(options1).get(option2).getAreaName();
                        cityId = AddrDbManager.options2Items.get(options1).get(option2).getId();
                        if (options3 >= 0) {
                            areaStr = AddrDbManager.options3Items.get(options1).get(option2).get(options3).getAreaName();
                            areaId = AddrDbManager.options3Items.get(options1).get(option2).get(options3).getId();
                        } else {
                            areaId = "-1";
                            areaStr = "";

                        }
                        mTvAddress.setText(provinceStr + cityStr + areaStr);
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .setOutSideCancelable(true)
                        .build();
                optionView.setPicker(AddrDbManager.options1Items, AddrDbManager.options2Items, AddrDbManager.options3Items);
            }
            optionView.show();
        } else {
            AndPermission.with(this).permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)

                    .onGranted(permissions -> {
                        ToastUtils.showToast("正在加载地址数据");
                        AddrDbManager.loadAddressData(AddressEditActivity.this);
                    })
                    .onDenied(permissions -> {
                        ToastUtils.showToast("为了功能正常使用，请您开启存储权限");
                    })
                    .start();
        }
    }

    @Override
    public void onListSuccess(AddressListBean bean) {

    }

    @Override
    public void onAddSuccess() {
        ToastUtils.showToast("地址添加成功");
        finish();
    }

    @Override
    public void onUpdateSuccess() {
        ToastUtils.showToast("地址编辑成功");
        finish();
    }

    @Override
    public void onDelSuccess() {

    }

    @Override
    public void onDefaultSuccess() {

    }

}
